#coding=utf-8
from PIL import Image
import json
# from chaojiying import Chaojiying_Client
# import pytesseract
# import sys
import requests
import time
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
# from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

browser = webdriver.Chrome()

# 还款计划
target_rap2_url = 'http://rap2.local:32600/organization/repository/editor?id=111&mod=785&itf=7929'


def convertStrTo_(url):
    pattern = r'^/api'
    replaceResult = re.sub(pattern, '', url)
    splitArr = replaceResult.split('/')
    i = 0
    for item in splitArr:
        if item == '':
            splitArr.pop(i)
        i = i + 1
    return '_'.join(splitArr)


def saveValidateImg(browser, imgOfValidateElm):
    location = imgOfValidateElm.location
    size = imgOfValidateElm.size
    print(1, size)
    browser.save_screenshot('H:\\tmp\\tmpPrintScreen.png')
    rangle = (
        int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height']))
    i = Image.open("H:\\tmp\\tmpPrintScreen.png")
    frame4 = i.crop(rangle)
    frame4.save("H:\\tmp\\savePrintScreen.png")
    time.sleep(1)


# 打印接口为前端需要的funciont格式
def print_js_script_01(itm):
    print('// ' + itm['name'])
    print('// ' + itm['url'])
    interfaceFnName = convertStrTo_(itm['url'])
    interFaceFnContent = """function {0}(params) {{
        const url = '{1}'
        return Vue.prototype.$http({{
            method: 'post',
            url,
            data: params
        }})
    }}
    """.format(interfaceFnName, itm['url'])
    print(interFaceFnContent)
    print('')


def for_print_js_script_01(interfaceArr):
    # 集中打印所有的接口
    for itm in interfaceArr:
        print(itm['url'])
    print('----------------------------------------------')
    for itm in interfaceArr:
        print_js_script_01(itm)


def getCookies(browser):
    requestsCookies = {}
    cookies = browser.get_cookies()
    for cookie in cookies:
        requestsCookies[cookie['name']] = cookie['value']
    return requestsCookies


def formatArrToStr(arr):
    s = '{\n'
    for item in arr:
        type1 = item['type']
        name = item['name']
        description = item['description']
        children = item['children']
        if (str(type(children)) == "<class 'list'>") and (len(children) > 0):
            s += ('"{0}":'.format(name) + formatArrToStr(children) + ',')
        else:
            s += '"{0}":"",  //  {1} {2}, '.format(name, type1, description) + '\n'
    s += '}'
    return s


try:
    CJY_CFG = None
    RAP2_CFG = None
    with open("E:\\projs\\my\\chaojiying.json", 'r') as f:
        CJY_CFG = json.load(f)
        f.close()
    with open("E:\\projs\\my\\rap2.json", 'r') as f2:
        RAP2_CFG = json.load(f2)
        f2.close()

    browser.get('http://rap2.local:32600/account/login')
    wait = WebDriverWait(browser, 10)
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.MuiList-root.MuiList-padding')))
    time.sleep(2)
    imgOfValidateElm = browser.find_element(By.CSS_SELECTOR, '.MuiList-root.MuiList-padding img[alt="captcha"]')
    saveValidateImg(browser, imgOfValidateElm)

    usernameInputEle = browser.find_element(By.CSS_SELECTOR, '.MuiList-root.MuiList-padding input[placeholder="Email"]') # placeholder = "Email"
    passwordInputEle = browser.find_element(By.CSS_SELECTOR, '.MuiList-root.MuiList-padding input[name="password"]')
    captchaInputEle = browser.find_element(By.CSS_SELECTOR, '.MuiList-root.MuiList-padding input[name="captcha"]')
    usernameInputEle.send_keys(RAP2_CFG['username'])
    passwordInputEle.send_keys(RAP2_CFG['passwd'])
    # captchaInputEle.send_keys('yzm1')
    # captchaInputEle.send_keys(Keys.ENTER)

    # # ## 超级鹰的代码，一般情况下不用，因为没积分
    # chaojiying = Chaojiying_Client(CJY_CFG['username'], CJY_CFG['passwd'], CJY_CFG['soft_id_01'])
    # im = open('H:\\tmp\\savePrintScreen.png', 'rb').read()
    # chaojiyingResult = chaojiying.PostPic(im, 1004) # 格式： {'err_no': 0, 'err_str': 'OK', 'pic_id': '8173315138316100001', 'pic_str': 'bf8o', 'md5': '05b24b2e3a1a8c15122e430f215129ce'}
    # captchaInputEle.send_keys(chaojiyingResult['pic_str'])
    # captchaInputEle.send_keys(Keys.ENTER)
    # time.sleep(1)

    time.sleep(15)
    browser.get(target_rap2_url)
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.InterfaceList')))
    interfaceEle = browser.find_element(By.CSS_SELECTOR, '.InterfaceList')
    interfaceArr = []
    interfaceWrappers = interfaceEle.find_elements(By.CSS_SELECTOR, '.sortable .Interface')

    for item in interfaceWrappers:
        try:
            aEl = item.find_element(By.CSS_SELECTOR, 'span a')
            aHref = aEl.get_attribute('href')
            name = item.find_element(By.CSS_SELECTOR, 'a .name').text
            url = item.find_element(By.CSS_SELECTOR, '.url').text
            interfaceArr.append({'name': name, 'url': url, 'aHref': aHref})
        except Exception:
            print(Exception)
    for_print_js_script_01(interfaceArr)

    print('----------------------------------------------')

    # 循环点击页面左侧的接口列表
    for linkWrapper in interfaceWrappers:
        leftRegionLinkAEle = linkWrapper.find_element(By.CSS_SELECTOR, 'span a')
        leftRegionLinkAHref = leftRegionLinkAEle.get_attribute('href')
        name = linkWrapper.find_element(By.CSS_SELECTOR, 'a .name').text
        aItem = linkWrapper.find_element(By.CSS_SELECTOR, 'a')
        url = linkWrapper.find_element(By.CSS_SELECTOR, '.url').text
        apiObj = {'name': name, 'url': url, 'aHref': leftRegionLinkAHref}
        print_js_script_01(apiObj)
        aItem.click()
        time.sleep(2)
        rightRegionUrl = browser.find_element(By.CSS_SELECTOR, 'article.InterfaceEditor > div.InterfaceSummary ul.summary li:nth-child(1) a').text
        if rightRegionUrl == url:
            # 获取接口id页面下的当前点击的接口的id， 通过 http://rap2.local:32601/interface/get?id=7934 获取内容
            reResult = re.match('.*id=(\d+)&mod=(\d+)&itf=(\d+)', leftRegionLinkAHref)
            id = reResult.group(3)
            # 通过request 获取接口对应的字段信息
            r = requests.request('get', 'http://rap2.local:32601/interface/get?id={0}'.format(id), cookies=getCookies(browser))
            jsonResult = r.json()
            requestProperties = jsonResult['data']['requestProperties']
            # 递归打印接口发送请求需要的字段
            print(formatArrToStr(requestProperties))

finally:
    print('finally')
#     browser.close()


